{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Trade derivatives\n",
    "\n",
    "## Derivatives Types\n",
    "There are three derivatives types available for trading at OKX. \n",
    "- Futures\n",
    "- Perpetual swaps\n",
    "- Options\n",
    "You can refer to [Derivatives Explained](https://www.okx.com/academy/en/bitcoin-derivatives-explained-futures-perpetual-swaps-and-options) for explanations and more information. \n",
    "We will use Perpetual swaps as examples in this tutorial.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Import API modules\n",
    "The following modules are available\n",
    "- Trade\n",
    "- BlockTrading\n",
    "- Funding\n",
    "- Account\n",
    "- Convert\n",
    "- Earning\n",
    "- SubAccount\n",
    "- MarketData\n",
    "- PublicData\n",
    "- TradingData\n",
    "- Status\n",
    "- NDBroker\n",
    "- FDBroker"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import okx.Trade as Trade"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Fill in your API key details"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "api_key = \"xxxxx\"\n",
    "secret_key = \"xxxxx\"\n",
    "passphrase = \"xxxxxx\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Get available funds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import okx.Funding as Funding\n",
    "\n",
    "flag = \"1\"  # live trading:0 , demo trading：1\n",
    "\n",
    "fundingAPI = Funding.FundingAPI(api_key, secret_key, passphrase, False, flag)\n",
    "\n",
    "result = fundingAPI.get_currencies()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Get market data\n",
    "You can also replace instType with \"FUTURES\" or \"OPTION\" for your information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import okx.MarketData as MarketData\n",
    "\n",
    "flag = \"1\"  # live trading: 0, demo trading: 1\n",
    "\n",
    "marketDataAPI = MarketData.MarketAPI(flag = flag)\n",
    "\n",
    "result = marketDataAPI.get_tickers(instType = \"SWAP\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Prepare for trading\n",
    "- Make sure you understand the basic trading rules. Please refer to [Basic Trading Rules](https://www.okx.com/support/hc/en-us/sections/360011507312)\n",
    "- Make sure you have enough funds in your trading account. Please refer to  [Get balance](https://www.okx.com/docs-v5/en/#rest-api-account-get-balance)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Get account balance. Please refer to  [Get balance](https://www.okx.com/docs-v5/en/#rest-api-account-get-balance)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import okx.Account as Account\n",
    "flag = \"1\"  # live trading: 0, demo trading: 1\n",
    "\n",
    "accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)\n",
    "\n",
    "result = accountAPI.get_account_balance()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Get available trading pairs from [Get instruments](https://www.okx.com/docs-v5/en/#rest-api-public-data-get-instruments).\n",
    "As in the same manner, choose the instType that you would like to get information for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import okx.PublicData as PublicData\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    flag = \"1\"  # live trading: 0, demo trading: 1\n",
    "\n",
    "    publicDataAPI = PublicData.PublicAPI(flag = flag)\n",
    "\n",
    "    result = publicDataAPI.get_instruments(instType = \"SWAP\")\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Get the current account configuration from the `acctLv` parameter in [Get account configuration](https://www.okx.com/docs-v5/en/#rest-api-account-get-account-configuration).\n",
    "In unified account, there are four account modes as we mentioned in the last tutorial: \n",
    "- Simple account,\n",
    "- Single-currency margin account, \n",
    "- Multi-currency margin account, \n",
    "- Portfolio margin account. \n",
    "\n",
    "Only the last three margin modes, namely, single-currency margin, multi-currency margin and portfolio margin, are eligible to trade derivatives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import okx.Account as Account\n",
    "\n",
    "flag = \"1\"  # live trading: 0, demo trading: 1\n",
    "\n",
    "accountAPI = Account.AccountAPI(api_key, secret_key, passphrase, False, flag)\n",
    "result = accountAPI.get_account_config()\n",
    "print(result)\n",
    "\n",
    "if result['code'] == \"0\":\n",
    "    acctLv = result[\"data\"][0][\"acctLv\"]\n",
    "    if acctLv == \"1\":\n",
    "        print(\"Simple mode\")\n",
    "    elif acctLv == \"2\":\n",
    "        print(\"Single-currency margin mode\")\n",
    "    elif acctLv == \"3\":\n",
    "        print(\"Multi-currency margin mode\")\n",
    "    elif acctLv == \"4\":\n",
    "        print(\"Portfolio margin mode\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set leverage via  [Set leverage](https://www.okx.com/docs-v5/en/#rest-api-account-set-leverage).\n",
    "You can refer to [OKX Margin Trading Rules](https://www.okx.com/support/hc/en-us/articles/360019908352--OKX-Margin-Trading-Rules).\n",
    "The leverage of a single currency, Leverage = position value / (balance in cross positions + unrealized P&L in cross margin positions).\n",
    "See [references of setting leverage](https://www.okx.com/trade-market/position/swap) for more information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set leverage to be 5x for all cross-margin BTC-USDT SWAP positions,\n",
    "# by providing any SWAP instId with BTC-USDT as the underlying\n",
    "result = accountAPI.set_leverage(\n",
    "    instId = \"BTC-USDT-SWAP\",\n",
    "    lever = \"5\",\n",
    "    mgnMode = \"cross\"\n",
    ")\n",
    "print(result)\n",
    "\n",
    "# Set leverage to be 5x for all isolated-margin BTC-USDT SWAP positions,\n",
    "# by providing any SWAP instId with BTC-USDT as the underlying\n",
    "result = accountAPI.set_leverage(\n",
    "    instId = \"BTC-USDT-SWAP\",\n",
    "    lever = \"5\",\n",
    "    mgnMode = \"isolated\"\n",
    ")\n",
    "print(result)\n",
    "\n",
    "# Set leverage to be 5x for an isolated-margin \n",
    "# BTC-USDT-SWAP long position;\n",
    "# This does NOT affect the leverage of any other BTC-USDT SWAP positions with different maturities or posSide\n",
    "result = accountAPI.set_leverage(\n",
    "    instId = \"BTC-USDT-SWAP\",\n",
    "    lever = \"5\",\n",
    "    posSide = \"long\",\n",
    "    mgnMode = \"isolated\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Start Derivatives Trading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "### Derivatives trading under single-currency margin/multi-currency margin/portfolio margin mode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import okx.Trade as Trade\n",
    "\n",
    "flag = \"1\"  # live trading: 0, demo trading: 1\n",
    "\n",
    "tradeAPI = Trade.TradeAPI(api_key, secret_key, passphrase, False, flag)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Place orders under different position (order placement) modes: long/short and buy/sell\n",
    "There are two position (order placement) modes when trading FUTURES and perpetual SWAP: long/short and buy/sell (net).\n",
    "You can change the position (order placement) mode between long/short and buy/sell (net), via the API [Set position mode](https://www.okx.com/docs-v5/en/#rest-api-account-set-position-mode):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = accountAPI.set_position_mode(\n",
    "    posMode=\"long_short_mode\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "### Place a limit order via [Place order](https://www.okx.com/docs-v5/en/#rest-api-trade-place-order)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# limit order\n",
    "result = tradeAPI.place_order(\n",
    "    instId=\"BTC-USDT-SWAP\",\n",
    "    tdMode=\"isolated\",\n",
    "    side=\"buy\",\n",
    "    posSide=\"net\",\n",
    "    ordType=\"limit\",\n",
    "    px=\"19000\",\n",
    "    sz=\"100\"\n",
    ")\n",
    "print(result)\n",
    "\n",
    "if result[\"code\"] == \"0\":\n",
    "    print(\"Successful order request，order_id = \",result[\"data\"][0][\"ordId\"])\n",
    "else:\n",
    "    print(\"Unsuccessful order request，error_code = \",result[\"data\"][0][\"sCode\"], \", Error_message = \", result[\"data\"][0][\"sMsg\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "### Place a market order"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# market order\n",
    "result = tradeAPI.place_order(\n",
    "    instId=\"BTC-USDT-SWAP\",\n",
    "    tdMode=\"isolated\",\n",
    "    side=\"buy\",\n",
    "    posSide=\"net\",\n",
    "    ordType=\"market\",\n",
    "    sz=\"100\"\n",
    ")\n",
    "print(result)\n",
    "\n",
    "if result[\"code\"] == \"0\":\n",
    "    print(\"Successful order request，order_id = \",result[\"data\"][0][\"ordId\"])\n",
    "else:\n",
    "    print(\"Unsuccessful order request，error_code = \",result[\"data\"][0][\"sCode\"], \", Error_message = \", result[\"data\"][0][\"sMsg\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cancel an order via [Cancel order](https://www.okx.com/docs-v5/en/#rest-api-trade-cancel-order)\n",
    "You also use clOrdId in place of ordId"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = tradeAPI.cancel_order(instId=\"BTC-USDT-SWAP\", ordId=\"505073046126960640\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Amend an order via [Amend order](https://www.okx.com/docs-v5/en/#rest-api-trade-amend-order)\n",
    "You also use clOrdId in place of ordId.\n",
    "This example shows the revision of a new size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = tradeAPI.amend_order(\n",
    "    instId=\"BTC-USDT-SWAP\", \n",
    "    ordId=\"505073046126960640\",\n",
    "    newSz=\"80\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get details/state of a certain order, please refer to [Get order details](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-details)\n",
    "Other than ordId, you can also specify clOrdId to get order details."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = tradeAPI.get_order(instId=\"BTC-USDT-SWAP\", ordId=\"505073046126960640\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## To get the list of open orders, please refer to [Get order List](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "result = tradeAPI.get_order_list()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## To get past orders，please refer to [Get order history (last 7 days)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-history-last-7-days) and [Get order history (last 3 months)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-order-history-last-3-months)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "result = tradeAPI.get_orders_history(\n",
    "    instType=\"SPOT\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "result = tradeAPI.get_orders_history_archive(\n",
    "    instType=\"SPOT\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## To get past trades，please refer to [Get transaction details (last 3 days)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-transaction-details-last-3-days) and [Get transaction details (last 3 months)](https://www.okx.com/docs-v5/en/#rest-api-trade-get-transaction-details-last-3-months)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "result = tradeAPI.get_fills(\n",
    "    instType = \"SWAP\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "result = tradeAPI.get_fills_history(\n",
    "    instType = \"SWAP\"\n",
    ")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Get positions via [Get positions](https://www.okx.com/docs-v5/en/#rest-api-account-get-positions)\n",
    "When your account is in net mode, net positions will be displayed, and when your account is in long/short mode, long or short positions will be displayed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = accountAPI.get_positions()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example, you can track your unrealized profit and loss through the response parameter upl."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.9 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.9"
  },
  "vscode": {
   "interpreter": {
    "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
